import { LocalStorage, LowSync } from 'lowdb'
import { cloneDeep } from 'lodash'
import cookies from './util.cookies'

const env = import.meta.env

function initDB() {
  const adapter = new LocalStorage(`taie-${env.VITE_APP_VERSION}`)
  const db = new LowSync(adapter)
  db.read()
  db.data = db.data || {}
  db.write()
  return db
}

export const DB = initDB()

/**
 * 数据库路径构建
 * @param dbName
 * @param path
 * @param user
 * @param defaultValue
 * @param validator
 * @returns {string}
 */
function pathInit({
  dbName = 'dataBase',
  path,
  user = true,
  defaultValue = '',
  validator = () => true
}) {
  const userId = cookies.get('userId') || 'ghost'
  const currentPath = `${dbName}.${user ? `user.${userId}` : 'public'}${path ? `.${path}` : ''}`
  const value = DB.data[currentPath]
  if (!(value !== undefined && validator(value))) {
    DB.data[currentPath] = defaultValue
    DB.write()
  }
  return currentPath
}

/**
 * 存储值
 * @param dbName
 * @param path
 * @param value
 * @param user
 */
export function dbSet({
  dbName = 'dataBase',
  path = '',
  value = '',
  user = false
}) {
  DB.data[pathInit({ dbName, path, user })] = value
  DB.write()
}

/**
 * 查询值
 * @param dbName
 * @param path
 * @param defaultValue
 * @param user
 * @returns {*}
 */
export function dbGet({
  dbName = 'dataBase',
  path = '',
  defaultValue = '',
  user = false
}) {
  return cloneDeep(DB.data[pathInit({ dbName, path, user, defaultValue })])
}

export function dbClear() {
  DB.data = {}
  DB.write()
}
